from pylons import c, config
from lxml import etree

from mtp import model

from mtp.lib.helpers import url_for

import logging
log = logging.getLogger(__name__)

def toc(arg, element):
    """ adds a table of contents to the page """
    tree = element.getroottree()

    levels = 2
    levels_str = "|".join(["h%d"%i for i in range(1, levels+1)])
    hs = tree.xpath('//%s' % levels_str)
    
    p = ol = etree.Element('ul')

    level = 1

    for h in hs:
        l = int(h.tag[1])
        if l > level:
            p = etree.SubElement(li, 'ul')
        elif l < level:
            p = p.getparent()

        anchor_name = h.text.replace(' ', '')
        h.set('id', anchor_name)

        li = etree.SubElement(p, 'li')
        a = etree.SubElement(li, 'a', href="#%s" % anchor_name)
        a.text = h.text
        level = l
    
    return ol


def test(arg, element):
    """ a simple test macro that prints its own arguments """
    return "TEST MACRO!!! arg=%s body='%s':)" % (arg, element.text)


def list_macros(arg, element):
    """ inserts a list of all available macros """
    dl = etree.Element('dl')
    all_macros = config['mtp.macros']
    names = all_macros.keys()
    names.sort()

    for name in names:
        h1 = etree.SubElement(dl, 'dt')
        h1.text = name
        p = etree.SubElement(dl, 'dd')
        p.text = all_macros[name].__doc__ or 'No help'

    return dl


def list_pages(arg, element):
    """ inserts a list of all known pages """

    ul = etree.Element('ul')
    
    pages = model.Page.getAll()
    for page in pages:
        li = etree.SubElement(ul, 'li')
        a = etree.SubElement(li, 'a', href=url_for('page', id=page.urlTitle()))
        a.text = page.title

    return ul



